package com.my.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.my.entity.QuestionOption;
import com.my.entity.Question;
import com.my.entity.Subject;
import com.my.service.QuestionOptionService;
import com.my.service.QuestionService;
import com.my.util.Rest;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@CrossOrigin
public class QuestionController {

    @Resource
    private QuestionService service;

    @Resource
    private QuestionOptionService qoService;

    @PostMapping("question/get")
    public Rest get(@RequestParam(defaultValue = "1") int pageNo, @RequestParam(defaultValue = "10") int pageSize, @RequestBody Question question) {
        return Rest.ok().setData("page", service.getPage(new Page<>(pageNo, pageSize), question));
    }

    @Transactional(rollbackFor = Exception.class)
    @PostMapping("questions")
    public Rest add(@RequestBody Question question) {
        if(service.save(question)) {
            for (QuestionOption option : question.getOptions()) {
                qoService.save(option.setQuestionId(question.getId()));
            }
            return Rest.ok("添加成功！");
        }
        return Rest.err("添加失败！");
    }

    @Transactional(rollbackFor = Exception.class)
    @PutMapping("questions")
    public Rest edit(@RequestBody Question question) {
        if(service.updateById(question)) {
            qoService.remove(new QueryWrapper<QuestionOption>().eq("question_id", question.getId()));
            for (QuestionOption option : question.getOptions()) {
                qoService.save(option.setQuestionId(question.getId()));
            }
            return Rest.ok("添加成功！");
        }
        return Rest.err("添加失败！");
    }

    @Transactional(rollbackFor = Exception.class)
    @DeleteMapping("questions")
    public Rest del(Long id) {
        if(service.removeById(id) && qoService.remove(new QueryWrapper<QuestionOption>().eq("question_id", id))) {
            return Rest.ok("删除成功！");
        }
        return Rest.err("删除失败！");
    }

    @GetMapping("getBySubject")
    public Rest getBySubject(Long subjectId) {
        return Rest.ok().setData("list", service.getBySubjectId(subjectId));
    }

}
